/*
 * This file is part of quickReminder, a software for gamers
 *
 * Copyright (C) 2006-2009 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

using LucasCode.PublicTypes;
using LucasCode.Tools;
using LucasCode.Win32;
using XPTable.Editors;
using XPTable.Models;
using IoWorker;

using Settings = GlobalSettings.Properties.Settings;

namespace quickReminder
{
    public partial class FormUpload : Form
    {
       // string m_Cookie = string.Empty;

        FileUploader fileUploader = new FileUploader();

        //StringCollection MapsPlayed = new StringCollection();
        
        MatchArchive m_Archive = new MatchArchive();
        
        public FormUpload(string archive): this(FileSerializer.loadMatchArchiveFromQmaFile(archive))
        {
            createArchiveToolStripMenuItem.Visible = false;
        }

        public FormUpload()
            : this(new MatchArchive())
        { }


        public FormUpload(MatchArchive archive)
        {
            InitializeComponent();
            m_Archive = archive;
            System.Diagnostics.Trace.WriteLine("Started FormUpload with Matcharchive: " + archive);
            if (m_Archive == null)
            {
                return;
            }
            InitDialog();

            RefreshView();
        }

        public new void Show()
        {
            if (m_Archive == null)
            {
                MessageBox.Show("Invalid Matchfile!");
                Close();
                return;
            }
            base.Show();
        }

        public FormUpload(string MatchURL, StringCollection FileList, ConsoleEventItemCollection events, string Gamename, string Modname)
        {
            System.Diagnostics.Trace.WriteLine("Started FormUpload for match " + MatchURL);

            InitializeComponent();
            
            
            Text += " - " + MatchURL;
            
            System.Diagnostics.Trace.WriteLine("Found " + events.Count + " events for this match");
            

            //m_GameVersion = gamever;
#if TEST_PLAYERPARSING && DEBUG
            m_Archive.Matchlink = "http://www.esl.eu/de/cs/5on5/mr12/ladder/match/8510087/";

            MatchPlayer p = new MatchPlayer("Chronicz");
            p.GameID = "0:0:11849927";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("paiN");
            p.GameID = "0:1:15823874";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("oLos");
            p.GameID = "0:1:9929224";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("HansDampf");
            p.GameID = "0:1:439954";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("evoexe");
            p.GameID = "0:1:3222719";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("Hoax");
            p.GameID = "0:0:291986";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("ruffoR");
            p.GameID = "0:0:6888909";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("tOrE");
            p.GameID = "0:1:9870342";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("HelD");
            p.GameID = "0:0:11647288";
            m_Archive.AddTeamlessPlayer(p);

            p = new MatchPlayer("Joe");
            p.GameID = "0:0:3654325";
            m_Archive.AddTeamlessPlayer(p);

            //RefreshView();

            /*ListViewItem p1 = new ListViewItem("bla", 0);
            p1.SubItems.Add("0:1:10936068");
            p1.SubItems.Add("");
            p1.SubItems.Add("");
            p1.SubItems.Add("none");
            //i.SubItems[4].Tag = "2507797";

            ListViewItem p2 = new ListViewItem("bla", 0);
            p2.SubItems.Add("0:1:1663189");
            p2.SubItems.Add("");
            p2.SubItems.Add("");
            p2.SubItems.Add("none");

            PlayerList.Items.Add(p1);
            PlayerList.Items.Add(p2);*/
            //PlayerList.Items.Add(p3);
#endif
            if (Properties.Settings.Default.UploadWindowSize.Height > 0 && Properties.Settings.Default.UploadWindowSize.Width > 0)
                Size = Properties.Settings.Default.UploadWindowSize;
            
            /*
            if (Properties.Settings.Default.UploadWindowPos.X >= 0 && Properties.Settings.Default.UploadWindowPos.Y >= 0)
                this.Location = Properties.Settings.Default.UploadWindowPos;*/
            //splitContainer1.SplitterDistance = Properties.Settings.Default.UploadWindowSplitterPos;
            
            //ParseConsole(events);
            m_Archive.Gamename = Gamename;
            m_Archive.Modname = Modname;
            m_Archive.Matchlink = MatchURL;


#if DEBUG || READEVENTSFROMFILE
            if (events.Count <= 0 && File.Exists("condumphl1.txt"))
            {

                var reader = new StreamReader("condumphl1.txt");
                while (!reader.EndOfStream)
                {
                    events.Add(new ConsoleEventItem(DateTime.Now, ConsoleEventItemType.None, reader.ReadLine()));
                }
                reader.Close();
            }

            if (!File.Exists("condumphl1.txt") && events.Count > 0)
            {
                var builder = new StringBuilder();

                foreach (ConsoleEventItem ev in events)
                {
                    builder.AppendLine(ev.EventText);
                }

                StreamWriter writer = File.CreateText("condumphl1.txt");
                writer.Write(builder.ToString());
                writer.Close();
            }
#endif
            //TODO: cleanup
            /*if (!string.IsNullOrEmpty(m_Archive.Gamename))
            {
                switch (m_Archive.Gamename.ToLower())
                {
                    case "hl":
                        var p = new ConsoleParserHL1();
                        p.Parse(events);
                        m_Archive.TeamlessPlayers = p.Players;

                        foreach (MatchPlayer player in p.Players)
                        {
                            System.Diagnostics.Trace.WriteLine("FormUpload() Player " + player.CurrentNick + " has " + player.Kills + " kills and " + player.Deaths + " death.");
                            if (player.Team != null)
                                System.Diagnostics.Trace.WriteLine("FormUpload() same Player with qrID " + player.QrID + " and team " + player.Team.Name);
                            else
                                System.Diagnostics.Trace.WriteLine("FormUpload() same Player with qrID " + player.QrID);
                        }

                        break;
                    case "hl2":
                        var hl2p = new ConsoleParserHL2();
                        hl2p.Parse(events);
                        m_Archive.TeamlessPlayers = hl2p.Players;
                        break;
                }
            }*/
#if DEBUG || READEVENTSFROMFILE
            //TODO: cleanup
            /*else
            {
                var p = new ConsoleParserHL1();
                p.Parse(events);
                m_Archive.TeamlessPlayers = p.Players;
            }*/
#endif

            foreach (string s in FileList)
            {
                m_Archive.AddFile(new MatchFile(s));
                System.Diagnostics.Trace.TraceInformation("Found file from match " + s);
            }
            m_Archive.AutoRenameFiles(events, new MatchArchive.ParseSettings(Properties.Settings.Default.AequitasTitle, Properties.Settings.Default.DemoVariationpercent));
            InitDialog();
            RefreshView();

            System.Diagnostics.Trace.TraceInformation("Finished FormUpload for match " + MatchURL);
        }

        private void InitDialog()
        {
            Parser.DoWork += new DoWorkEventHandler(Parser_DoWork);
            MatchInfoUpdater.DoWork += new DoWorkEventHandler(Parser_DoWork);
            fileUploader.FileProgressChanged += new EventHandler<UploadFile.ProgressChangedEventArgs>(fileUploader_FileProgressChanged);
            fileUploader.FileUploadComplete += new EventHandler(fileUploader_UploadComplete);
            //m_Cookie = Properties.Settings.Default.Cookie;
            //m_Archive.LoginCookie = Properties.Settings.Default.Cookie;
            if (string.IsNullOrEmpty(m_Archive.Matchlink))
                tabControl1.TabPages.Remove(tabOverview);
        }
        
        private void fileUploader_UploadComplete(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new EventHandler(fileUploader_UploadComplete), new object[] { sender, e });
                return;
            }
            //UploadProgress.Visible = false;
            UploadStatusText.Text = "Uploader idle.";
            startUploadToolStripMenuItem1.Visible = true;
            cancelAllUploadsToolStripMenuItem.Visible = false;
            cancelSelectedUploadsToolStripMenuItem.Visible = false;
            //UploadStatusText.Visible = false;
            //lwFileList.CheckBoxes = true;
            cbUpload.Enabled = true;
            xpFiles.BeginUpdate();
            foreach (Row row in xpFiles.TableModel.Rows)
            {
                if (row.Tag == null)
                    continue;
                MatchFile f = row.Tag as MatchFile;
                if (f == null)
                    continue;
                if (row.Cells[0].Checked)
                {
                    row.Editable = true;
                    if (f.WasUploaded)
                    {
                        row.Cells[1].Image = lang.apply16;
                        row.Cells[0].Checked = false;

                    }
                    else
                    {
                        row.Cells[1].Image = lang.button_cancel;
                    }
                }
                
            }
            xpFiles.EndUpdate();
            startUploadToolStripMenuItem.Enabled = true;
        }

        private void fileUploader_FileProgressChanged(object sender, UploadFile.ProgressChangedEventArgs e)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new EventHandler<UploadFile.ProgressChangedEventArgs>(fileUploader_FileProgressChanged), new object[] { sender, e });
                return;
            }
            xpFiles.BeginUpdate();
            foreach (Row r in xpFiles.TableModel.Rows)
                if (r.Tag == e.File.MatchFile)
                    UpdateFileRow(r, e.File);
            xpFiles.EndUpdate();
        }

        private void UpdateFileRow(Row r, UploadFile file)
        {
            r.Cells[4].Text = file.Status;
            r.Cells[5].Data = file.Progress;// file.Progress;
            r.Cells[6].Text = Math.Round(file.Speed/1000.0, 2).ToString() + "kb/s"; //file.Speed.ToString() + "kb/s";
        }

        private Image GetMapImage(string map, string game)
        {
            try
            {
                if (File.Exists(Path.Combine(Path.Combine("maps", game), map + ".jpg")))
                    return Image.FromFile(Path.Combine(Path.Combine("maps", game), map + ".jpg"));
                System.Resources.ResourceManager res = new System.Resources.ResourceManager("quickReminder.maps" + game.ToLower(), GetType().Assembly);
                return (Image)res.GetObject(map);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Loading image for " + map + " failed.");

                return null;
            }
        }

        public delegate void RefreshViewInvoker();

        private void RefreshView()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new RefreshViewInvoker(RefreshView));
                return;
            }

            System.Diagnostics.Trace.WriteLine("RefreshView() started at " + DateTime.Now);

            MatchArchive archive = m_Archive;
            if (!string.IsNullOrEmpty(archive.Filename))
                Text = Path.GetFileName(archive.Filename);
            else if (!string.IsNullOrEmpty(archive.Matchlink))
                Text = archive.Matchlink;
            else
                Text = "Match Overview";
            if (archive.Contestants.Length > 0)
                Text += " - " + archive.Contestants[0].Name;
            if (archive.Contestants.Length > 1)
                Text += " vs " + archive.Contestants[1].Name;

            if (archive.Contestants.Length > 0)
            {
                if (archive.Contestants[0].Type == MatchContestantTypes.Individual)
                    Logo1.Height = 133;
                else
                    Logo1.Height = 100;
                Logo1.Image = archive.Contestants[0].Logo;
                Logo1.Tag = archive.Contestants[0].URL;

                lTeam1Name.Text = archive.Contestants[0].Name;

                if (archive.Contestants[0] == archive.Winner)
                    lTeam1Name.ForeColor = Color.Green;
                else if (archive.Winner != null)
                    lTeam1Name.ForeColor = Color.Red;
                else
                    lTeam1Name.ForeColor = SystemColors.ControlText;

                if (archive.Contestants.Length > 1)
                {
                    if (archive.Contestants[1].Type == MatchContestantTypes.Individual)
                        Logo2.Height = 133;
                    else
                        Logo2.Height = 100;
                    Logo2.Image = archive.Contestants[1].Logo;
                    Logo2.Tag = archive.Contestants[1].URL;
                    lTeam2Name.Text = archive.Contestants[1].Name;

                    if (archive.Contestants[1] == archive.Winner)
                        lTeam2Name.ForeColor = Color.Green;
                    else if (archive.Winner != null)
                        lTeam2Name.ForeColor = Color.Red;
                    else
                        lTeam2Name.ForeColor = SystemColors.ControlText;

                }
            }

            //for more than 1 round in archive.Rounds check if one of them is 0-0, if so delete
            if (archive.Rounds.Length > 1)
            {
                for (int i = 0; i < archive.Rounds.Length; i++)
                {
                    if (archive.Rounds[i].Scores[0] == 0 && archive.Rounds[i].Scores[1] == 0)
                        archive.RemoveRound(archive.Rounds[i]);
                }
            }

            if (archive.Rounds.Length > 0)
            {
                s1.Text = archive.Rounds[0].Scores[0].ToString();
                s2.Text = archive.Rounds[0].Scores[1].ToString();
                lMap1.Text = archive.Rounds[0].Map;
                if (!string.IsNullOrEmpty(m_Archive.Gamename))
                    pMap1.Image = GetMapImage(archive.Rounds[0].Map, m_Archive.Gamename);
                //if (File.Exists(Path.Combine("maps", archive.Rounds[0].Map + ".jpg")))
                //pMap1.LoadAsync(Path.Combine("maps", archive.Rounds[0].Map + ".jpg"));
                //else
                //pMap1.Image = (Bitmap)LucasCode.Properties.Resources.ResourceManager.GetObject(lMap1.Text);
                if (archive.Rounds.Length > 1)
                {
                    s3.Visible = true;
                    s4.Visible = true;
                    //label3.Visible = true;
                    lMap2.Visible = true;
                    pMap2.Visible = true;
                    s3.Text = archive.Rounds[1].Scores[0].ToString();
                    s4.Text = archive.Rounds[1].Scores[1].ToString();
                    lMap2.Text = archive.Rounds[1].Map;

                    if (!string.IsNullOrEmpty(m_Archive.Gamename))
                        pMap2.Image = GetMapImage(archive.Rounds[1].Map, m_Archive.Gamename);
                    //if (File.Exists(Path.Combine("maps", archive.Rounds[1].Map + ".jpg")))
                    //pMap1.LoadAsync(Path.Combine("maps", archive.Rounds[1].Map + ".jpg"));
                    //else
                    //pMap2.Image = (Bitmap)LucasCode.Properties.Resources.ResourceManager.GetObject(lMap2.Text);
                }
                else
                {
                    s3.Visible = false;
                    s4.Visible = false;
                    //label3.Visible = false;
                    lMap2.Visible = false;
                    pMap2.Visible = false;
                }
            }

            if (!tabControl1.TabPages.Contains(tabOverview) && !string.IsNullOrEmpty(m_Archive.Matchlink))
                tabControl1.TabPages.Add(tabOverview);
            RefreshFileList();
            
            System.Diagnostics.Trace.WriteLine("RefreshView() finished at " + DateTime.Now);

            UpdateStats(m_Archive.Players);
        }

        private void RefreshFileList()
        {
            xpFiles.TableModel.Rows.Clear();
            foreach (MatchFile f in m_Archive.Files)
            {
                xpFiles.TableModel.Rows.Add(getFileRow(f));
                System.Diagnostics.Trace.WriteLine("RefreshFileList() Added " + f.TargetName + " to filelist in FormUpload");
            }
        }

        private Row getFileRow(MatchFile f)
        {
            Row r = new Row();

            r.Cells.Add(new Cell(string.Empty, !f.WasUploaded && f.WasAutoRenamed && (f.FileType == MatchFileType.Screenshot || f.FileType == MatchFileType.Aequitas)));
            r.Cells.Add(new Cell(string.Empty, Shell32.GetFiletypeIcon(f.Filename, false)));

            r.Cells[r.Cells.Count - 1].ImageSizeMode = ImageSizeMode.Normal;
            r.Cells.Add(new Cell(f.TargetName, lang.about_16));
            //ListViewItem i = new ListViewItem(name);
            r.Cells[r.Cells.Count - 1].Tag = f;
            r.Tag = f;

            //i.ToolTipText = Path.GetFileName(s);
            r.Cells.Add(new Cell(getFormattedKiloBytes(f.Size) + "kB"));

            r.Cells.Add(new Cell("Idle")); //Status 2
            r.Cells.Add(new Cell()); //Progress 3
            r.Cells.Add(new Cell()); //Speed 4
            //r.Cells.Add(new Cell()); //Time Remaining 5
            return r;
        }

        private void Parser_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                WebSynchronizer.MergePlayers(m_Archive);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //ThreadPool.QueueUserWorkItem(new WaitCallback(ParsePlayers), e.Argument);
#if !DEBUG
            //ParsePlayers(e.Argument);
#endif
        }

        //private MatchPlayer GetPlayer(List<MatchPlayer> players,  string name)
        //{
        //    foreach (MatchPlayer p in players)
        //    {
        //        if (p.CurrentNick == name)
        //        {
        //            return p;
        //        }
        //    }
        //    MatchPlayer pl = new MatchPlayer(name);
        //    players.Add(pl);
        //    return pl;
        //}

        public delegate void UpdateStatsInvoker(MatchPlayer[] players);

        private void UpdateStats(MatchPlayer[] players)
        {
            if(InvokeRequired)
            {
                BeginInvoke(new UpdateStatsInvoker(UpdateStats), new object[] { players });
                return;
            }

            xpStatistics.BeginUpdate();
            StatTableTM.Rows.Clear();
            //xpStatistics.SuspendLayout();
            foreach (MatchPlayer p in players)
            {
                Row r = new Row();
                r.Tag = p;
                if (p.IsBarred)
                    r.BackColor = Color.MistyRose;
                Cell c = new Cell(p.CurrentNick, lang.user16);
                c.ToolTipText = String.Join(Environment.NewLine, p.Names);
                c.WordWrap = false;
                r.Cells.Add(c);
                r.Cells.Add(p.GameID);
                if (!string.IsNullOrEmpty(p.ESLNick))
                {
                    c = new Cell(p.ESLNick);
                    c.Tag = p.UserID;
                    r.Cells.Add(c);
                }
                else
                    r.Cells.Add("<n/a>");

                c = new Cell("");
                c.ImageSizeMode = ImageSizeMode.ScaledToFit;
                if (!string.IsNullOrEmpty(m_Archive.Matchlink))
                {
                    if (p.HasAequitasLog)
                    {
                        c.Image = lang.aequitas16;
                        c.ToolTipText = "aequitas log available";
                    }
                    else
                    {
                        c.Image = lang.noaequitas16;
                        c.ToolTipText = "No aequitas log found!";
                    }
                }
                r.Cells.Add(c);
                    
                r.Cells.Add(new Cell(p.Kills));
                r.Cells.Add(new Cell(p.Headshots));
                if (p.Kills > 0)
                    r.Cells.Add(new Cell((int)Math.Round(((double)p.Headshots / p.Kills) * 100)));
                else
                    r.Cells.Add(new Cell(0));
                r.Cells.Add(new Cell(p.Deaths));
                //if (p.Deaths > 0)

                if (p.Deaths > 0)
                    r.Cells.Add(new Cell(Convert.ToString(Math.Round((double)p.Kills / p.Deaths, 2))));
                else if (p.Kills <= 0)
                    r.Cells.Add("");
                else
                    r.Cells.Add("∞");
                //else
                //r.Cells.Add(new Cell(double.PositiveInfinity.ToString()));
                StatTableTM.Rows.Add(r);
                //Row subrow = 
                
                //r.SubRows.Add(GetPlayerDetailsRow(p));
                //r.ExpandSubRows = false;
                //r.SubRows.Add(new Row(new string[] { "0", "0", "0" }));
            }
            xpStatistics.EndUpdate();
            //xpStatistics.ResumeLayout();
        }

        //private Row GetPlayerDetailsRow(MatchPlayer p)
        //{
        //    Row r = new Row();
        //    r.BackColor = Color.WhiteSmoke;
        //    r.Cells.Add(new Cell());
        //    string nickinfo = "All Nicks: ";
        //    foreach (string s in p.Names)
        //    {
        //        nickinfo += s + " / ";
        //    }
        //    Cell c = new Cell(nickinfo);
        //    c.ColSpan = 6;
        //    r.Cells.Add(c);
        //    return r;
        //}

        private string FromHL2String(string input)
        {
            UTF8Encoding u = new UTF8Encoding();
            //Encoding e = Encoding.GetEncoding(1252);
            Encoding e = Encoding.GetEncoding(1252);
            return u.GetString(e.GetBytes(input));
        }   

        private void FormUpload_Load(object sender, EventArgs e)
        {
            if (File.Exists("developer.secret"))
                return;
#if !DEBUG
            if (Settings.Default.Cookie == string.Empty)
            {
                MessageBox.Show("You must be logged in in order to use the automatic upload!");
                this.Close();
            }
#endif
        }

        public string getFormattedKiloBytes(long Bytes)
        {
            StringBuilder b = new StringBuilder();
            b.Append(Math.Round(Bytes / (double)1000, 0).ToString());
            int sl = b.Length;
            for (int i = sl; i > 0; i--)
            {
                if (sl - i > 0 && (sl - i) % 3 == 0)
                    b.Insert(i, ".");
            }
            return b.ToString();
        }

        private void FormUpload_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (fileUploader.UploadsRunning > 0)
            {
                if (MessageBox.Show(this, lang.QuitQuestion, lang.AreYouSure, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    fileUploader.CancelUploads();
                else
                    e.Cancel = true;
            }
        }

        private void startUploadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //fileUploader.LoginCookie = Properties.Settings.Default.Cookie;
            bool uploading = false;
            foreach (Row row in xpFiles.TableModel.Rows)
            {
                if (row.Cells[0].Checked)
                {
                    uploading = true;
                    break;
                }
            }
            if (!uploading || m_Archive.Matchlink == null)
                return;
            startUploadToolStripMenuItem.Enabled = false;
            startUploadToolStripMenuItem1.Visible = false;
            cancelAllUploadsToolStripMenuItem.Visible = true;
            cancelSelectedUploadsToolStripMenuItem.Visible = true;
            
            cbUpload.Enabled = false;
            foreach (Row row in xpFiles.TableModel.Rows)
            {
                //row.Cells[0].Enabled = false;
                if (!row.Cells[0].Checked)
                    continue;
                fileUploader.AddMatchFileToQueue((MatchFile)row.Tag);//.StartUpload((MatchFile)row.Tag);

                row.Editable = false;
            }

            fileUploader.StartUpload(Settings.Default.Cookie, m_Archive.Matchlink);

            UploadStatusText.Visible = true;
            UploadStatusText.Text = "Uploading";
        }

        private void changeMatchlinkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new FormEditString())
                m_Archive.Matchlink = f.ShowDialog(this, m_Archive.Matchlink);
            
            Text = m_Archive.Matchlink;
            //up.MatchURL = m_Archive.Matchlink;
        }

        private static void lwFileList_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void lwFileList_DragDrop(object sender, DragEventArgs e)
        {
            Array a = (Array)e.Data.GetData(DataFormats.FileDrop);
            if (a != null)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    string s = a.GetValue(i).ToString();
                    //AddFileToList(xpFiles.TableModel, s, true);
                    MatchFile newfile = new MatchFile(s);
                    m_Archive.AddFile(newfile);
                    Row r = getFileRow(newfile);
                    r.Cells[0].Checked = true;
                    xpFiles.TableModel.Rows.Add(r);
                }
            }
            
        }

        private void checkPlayersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StartParser();
        }

        private void FormUpload_FormClosed(object sender, FormClosedEventArgs e)
        {
            bool retry = true;
            int retries = 0;
            if (!string.IsNullOrEmpty(m_Archive.Filename))
                while (retry)
                {
                    try
                    {
                        //?? was wird hier getan?
                        //?? wieso soll hier etwas geschrieben werden, wenn doch die Form geschlossen wird?
                        //siehe FileSerializer "???"
                        //m_Archive.WriteArchiveDetails();
                        retry = false;
                    }
                    catch (Exception ex)
                    {
                        retries++;
                        if (retries > 1)
                            retry = MessageBox.Show(this, ex.Message, "Error writing archive!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) == DialogResult.Retry;
                    }
                }
                
            Properties.Settings.Default.UploadWindowSize = Size;
            Properties.Settings.Default.UploadWindowPos = DesktopLocation;
            Dispose();
        }

        private void FormUpload_Shown(object sender, EventArgs e)
        {
            this.Activate();
#if !DEBUG || TEST_PLAYERPARSING
            StartParser();
#endif
        }

        private void StartParser()
        {
            WorkProgress.Visible = true;
            ParseStatusText.Text = "Parsing website";
            ParseStatusText.Visible = true;
            Parser.RunWorkerAsync();
        }

        private void updateMatchInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(m_Archive.Matchlink))
            {
                try
                {
                    MatchInfoUpdater.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                WorkProgress.Visible = true;
            }
            else
            {
                MessageBox.Show("Kein Matchlink vorhanden, bitte geben sie erst den Link ein bevor sie updaten.");
            }
        }

        private void MatchInfoUpdater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (WorkProgress == null || !Visible)
                return;
            if (e.Error != null)
            {
                if (e.Error is System.Net.WebException)
                    MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(e.Error.StackTrace, e.Error.Message);
            }
            WorkProgress.Visible = false;
            RefreshView();
        }

        private void MatchInfoUpdater_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                m_Archive = WebSynchronizer.UpdateDetailsFromWeb(Settings.Default.Cookie, MatchInfoFlags.AequitasInfo |
                MatchInfoFlags.MapInfo |
                MatchInfoFlags.PlayerInfo |
                MatchInfoFlags.ScoreInfo |
                MatchInfoFlags.TeamInfo,m_Archive);
            }
            //?? hier sollte versucht werden etwas abzufangen ODER?
            catch
            {
            }
        }

        private static void Logo_Click(object sender, EventArgs e)
        {
            Control logo = sender as Control;

            if (logo.Tag != null && logo.Tag is string && !string.IsNullOrEmpty((string)logo.Tag))
            {
                try
                {
                    Process.Start((string)logo.Tag);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.StackTrace, ex.Message);
                }
            }
        }

        private void Parser_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                WorkProgress.Visible = false;
                ParseStatusText.Text = "Parser idle.";
                ParseStatusText.Visible = false;
                RefreshView();
                //wird in RefreshView() schon aufgerufen
                //UpdateStats(m_Archive.Players);
            }
            catch{}
            if (e.Error != null)
                MessageBox.Show(e.Error.StackTrace, e.Error.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private static void xpFiles_BeginEditing(object sender, XPTable.Events.CellEditEventArgs e)
        {
            if (e.Column == 2)
            {
                ((ComboBoxCellEditor)e.Editor).MaxDropDownItems = 10;
                ((ComboBoxCellEditor)e.Editor).DropDownStyle = DropDownStyle.DropDown;
                ((ComboBoxCellEditor)e.Editor).Items.Clear();
                foreach (string s in Properties.Settings.Default.PredefinedFilenames)
                    ((ComboBoxCellEditor)e.Editor).Items.Add(s);
                ((ComboBoxCellEditor)e.Editor).Items.Add(Properties.Settings.Default.AequitasTitle);
            }
        }

        private void xpFiles_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                xpFiles.TableModel.Rows.RemoveRange(xpFiles.SelectedItems);
        }

        private static void xpFiles_EditingStopped(object sender, XPTable.Events.CellEditEventArgs e)
        {
            if (e.Column == 2)
            {
                ((MatchFile)e.Cell.Row.Tag).TargetName = (string)((ComboBoxCellEditor)e.Editor).Text;
            }
        }

        private void viewESLProfileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach(Row r in xpStatistics.SelectedItems)
            {
                if (r.Cells[2].Tag != null)
                    try { Process.Start("http://www.esl.eu/player/" + (string)r.Cells[2].Tag + "/"); }
                    catch { }
                else
                    MessageBox.Show("No ESL account associated with this player!");
                    
            }
        }

        private void cancelAllUploadsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fileUploader.CancelUploads();
        }

        private void cancelSelectedUploadsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Row r in xpFiles.SelectedItems)
                ((UploadFile)r.Tag).Cancel();
        }

        private void xpFiles_DoubleClick(object sender, EventArgs e)
        {
            foreach (Row r in xpFiles.SelectedItems)
                try
                {
                    MatchFile f = r.Tag as MatchFile;
                    if (FileSerializer.IsFileArchived(f.Filename))
                    {
                        if (!string.IsNullOrEmpty(f.OldFilename) && File.Exists(f.OldFilename))
                            Process.Start(f.OldFilename);
                        else
                            MessageBox.Show("You can't view archived filecontents (yet)!");
                    }
                    else
                        Process.Start(f.Filename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

        private void createArchiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Row r in xpFiles.TableModel.Rows)
                if (r.Cells[0].Checked)
                    ((MatchFile)r.Tag).AddToArchive = true;
            using (FormCreateArchive f = new FormCreateArchive(m_Archive))
                f.ShowDialog();
        }
    }
}